package main

import (
	"fmt"
	"gitee.com/Diegoh/go-study/go-sync/singleton"
	"sync"
	"sync/atomic"
	"time"
)

var (
	once sync.Once
	wg   sync.WaitGroup
)

func main() {
	onceBody := func() {
		fmt.Println("i a only one")
	}

	done := make(chan bool, 10)

	for i := 0; i < 10; i++ {
		go func() {
			once.Do(onceBody)
			done <- true
		}()
	}
	for i := 0; i < 10; i++ {
		<-done
	}

	for i := 0; i < 10; i++ {
		wg.Add(1)
		go getAddr()
	}
	wg.Wait()

	//测试原子操作 atomic
	c3 := AutomicCounter{}
	testAtomic(&c3)
}

//获取单例地址
func getAddr() {
	defer wg.Done()
	ss := singleton.GetInstance()
	fmt.Println(ss)
}

//原子操作接口
type Counter interface {
	Inc()
	Load() int64
}

//实现接口
type AutomicCounter struct {
	counter int64
}

func (a *AutomicCounter) Inc() {
	atomic.AddInt64(&a.counter, 1)
}
func (a *AutomicCounter) Load() int64 {
	return atomic.LoadInt64(&a.counter)
}

//多线程 原子操作测试,将c 执行100次 原子操作，数值加一 所以说100
func testAtomic(c Counter) {
	var wg sync.WaitGroup
	start := time.Now()
	for i := 0; i < 100; i++ {
		wg.Add(1)
		go func() {
			c.Inc()
			wg.Done()
		}()
	}
	wg.Wait()
	end := time.Now()
	fmt.Printf("100次原子累加结果：%d，消耗时间：%v", c.Load(), end.Sub(start))
}
